<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端测试</title>
</head>
<body>
<div><label for="userId">用 户 Id：</label><input id="userId" name="用户Id" type="text"></div>
<div><label for="contentText">输入内容：</label><input id="contentText" name="输入内容" type="text"></div>
<p>【操作】：
<div>
    <button type="button" onclick="sendMessage()">发送消息</button>
</div>
</body>

<script type="text/javascript">
    var socket;
    if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        var userId = document.getElementById("userId").value;
        var reqUrl = "http://192.168.31.77:9100/ins/websocket"; //服务接口见：com.thfw.server.manager.WebSocketManager
        socket = new WebSocket(reqUrl.replace("http", "ws"));
        //打开事件
        socket.onopen = function () {
            console.log("Socket 已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function (msg) {
            console.log("onmessage--" + msg.data);

        };
        //关闭事件
        socket.onclose = function () {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }
    }

    function sendMessage() {
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            var userId = document.getElementById('userId').value;
            var contentText = document.getElementById('contentText').value;
            var msg = '{"userId":"' + userId + '","message":"' + contentText + '"}';
            console.log(msg);
            socket.send(msg);
        }
    }

</script>
</html>

